#!/usr/bin/env bash
set -e

# Parse arguments
for p in "$@"; do
	case "$p" in
		--with-plugins)
			WITH_PLUGINS=true
			shift
			;;
		--with-libs)
			WITH_LIBS=true
			shift
			;;
		--backend=*)
			value="${p#*=}"
			BACKEND="$value"
			shift
			;;
		-*)
			>&2 echo "Invalid option: $p"
			exit 255
			;;
	esac
done

PROJECT_DIR="$1"
# Check if project path is provided
[[ -z "$PROJECT_DIR" ]] && echo 'Enter path of project to create. Example: ./create-app ./app' && exit 255

# Check if project directory exists
[[ -e "$PROJECT_DIR" ]] && echo "Project dir '$PROJECT_DIR' already exist" && exit 255

kc_dir=$(cd "$(dirname "$0")" && pwd)

# Set default type to swoole due to fpm is deprecated but still possible to use
project_type=${BACKEND:-"swoole"}
[[ "$project_type" != "fpm" && "$project_type" != "swoole" ]] && echo "The type '$project_type' is not supported" && exit 255

# shellcheck source=./func.sh
source "$kc_dir/func.sh"

echo -e '\e[1;35mCopy skeleton to project dir\e[0m'
mkdir "$PROJECT_DIR"
cp -vr "$kc_dir"/skel/base/. "$PROJECT_DIR"
cp -vr "$kc_dir"/skel/"$project_type"/. "$PROJECT_DIR"
cp -vr "$kc_dir"/bin/. "$PROJECT_DIR"/bin
mkdir -p "$PROJECT_DIR"/env/{tmp,var,run,log,etc,backup}
echo '...done'

echo -e '\e[1;35mConfigure etc templates\e[0m'
app_dir=$PROJECT_DIR'/app'
epoch=$(date +%s)
secret_key=$(ssh_random_string 'A-Za-z0-9' 64)
# Copy yoda folder for containerization
sed "s|{{KISS_PROJECT}}|${PROJECT_DIR##*/}|g" "$kc_dir/skel/base/docker/.yodarc" \
  > "$PROJECT_DIR/docker/.yodarc"
# Replace global static variables for init project
sed "s|{{KISS_EPOCH}}|$epoch|g" "$kc_dir/skel/base/app/config/app.yml.tpl" \
  | sed "s|{{KISS_SECRET_KEY}}|$secret_key|g" \
  | sed "s|{{KISS_PROJECT_TYPE}}|$project_type|g" \
  > "$app_dir/config/app.yml.tpl"
echo '...done'

echo -e '\e[1;35mInstall compiled core file to project\e[0m'

args=()

if [[ "$WITH_PLUGINS" == "true" ]]; then
	args+=(--with-plugins)
fi

if [[ "$WITH_LIBS" == "true" ]]; then
	args+=(--with-libs)
fi

"$kc_dir"/install-core "${args[@]}" "$PROJECT_DIR"
echo '...done'

